//
//  WmcRecognitionSettingsView.swift
//  YPWatermarkCamera
//
//  Created by 周诗松 on 2022/10/18.
//

import UIKit
import YPBedrock

// MARK: - [WmcRecognitionSettingsView]

class WmcRecognitionSettingsView: UIView {
    // Internal

    var model: WmcWatermarkDetailModel?

    var confirmClosure: ((WmcWatermarkDetailModel) -> Void)?

    @discardableResult
    static func showInView(_ view: UIView, model: WmcWatermarkDetailModel?) -> WmcRecognitionSettingsView {
        let subview = WmcRecognitionSettingsView()
        subview.model = model
        subview.makeUI()
        subview.makeConstraints()
        subview.bindEvent()

        view.addSubview(subview)

        subview.snp.makeConstraints { make in
            make.top.left.bottom.right.equalToSuperview()
        }

        subview.layoutIfNeeded()

        UIView.animate(withDuration: 0.18, delay: 0.1, options: .curveEaseOut) {
            subview.backgroundColor = .wmc_grayH2_323233.yp.alpha(0.7)
            subview.contentView.snp.updateConstraints { make in
                make.bottom.equalTo(-20)
            }
            subview.layoutIfNeeded()
        } completion: { _ in
            UIView.animate(withDuration: 0.08, delay: 0.0, options: .curveEaseOut) {
                subview.contentView.snp.updateConstraints { make in
                    make.bottom.equalTo(0)
                }
                subview.layoutIfNeeded()
            }
        }

        return subview
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        let maskPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: 8.yp.cgSize)
        maskLayer.path = maskPath.cgPath
        contentView.layer.mask = maskLayer
    }

    func dismiss() {
        UIView.animate(withDuration: 0.2, delay: 0.1, options: .curveEaseOut) {
            self.backgroundColor = .wmc_grayH2_323233.yp.alpha(0.7)
            self.contentView.snp.updateConstraints { make in
                make.bottom.equalTo(420)
            }
            self.layoutIfNeeded()
        } completion: { _ in
            self.removeFromSuperview()
        }
    }

    // Private

    private lazy var viewModel: WmcRecognitionSettingsVM = {
        let vm = WmcRecognitionSettingsVM(model: model)
        return vm
    }()

    private lazy var contentView: UIView = {
        let view = UIView()
        view.backgroundColor = .wmc_white_FFFFFF
        return view
    }()

    private lazy var maskLayer: CAShapeLayer = {
        let maskLayer = CAShapeLayer()
        return maskLayer
    }()

    private lazy var cancelBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("取消", for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: .medium)
        btn.setTitleColor(.wmc_grayH2_323233, for: .normal)
        return btn
    }()

    private lazy var sureBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("确定", for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: .medium)
        btn.setTitleColor(.wmc_blue_5290FD, for: .normal)
        return btn
    }()

    private lazy var tableView: UITableView = {
        let view = UITableView(frame: CGRect.zero, style: .plain)
        view.backgroundColor = .wmc_white_FFFFFF
        view.delegate = self
        view.dataSource = self
        view.register(WmcRecognitionSettingsListCell.self, forCellReuseIdentifier: "WmcRecognitionSettingsListCell")
        view.separatorStyle = .none
        view.showsVerticalScrollIndicator = false
        return view
    }()

    private lazy var editFieldContentView: WmcEditFieldContentView = {
        let view = WmcEditFieldContentView()
        return view
    }()

    private func makeUI() {
        backgroundColor = .wmc_grayH2_323233.yp.alpha(0.0)

        addSubview(contentView)
        contentView.addSubview(cancelBtn)
        contentView.addSubview(sureBtn)
        contentView.addSubview(tableView)
    }

    private func makeConstraints() {
        contentView.snp.makeConstraints { make in
            make.height.equalTo(420)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(420)
        }

        cancelBtn.snp.makeConstraints { make in
            make.top.equalTo(14)
            make.left.equalTo(16)
            make.width.equalTo(32)
            make.height.equalTo(21)
        }

        sureBtn.snp.makeConstraints { make in
            make.top.equalTo(14)
            make.right.equalTo(-16)
            make.width.equalTo(32)
            make.height.equalTo(21)
        }

        tableView.snp.makeConstraints { make in
            make.top.equalTo(48)
            make.left.right.bottom.equalToSuperview()
        }
    }

    private func bindEvent() {
        cancelBtn.yp.addEvent { [weak self] _ in
            guard let weakSelf = self, let model = weakSelf.model else { return }
            weakSelf.saveConfig(model)
            weakSelf.dismiss()
        }

        sureBtn.yp.addEvent { [weak self] _ in
            guard let weakSelf = self, let model = weakSelf.model else { return }
            weakSelf.saveConfig(model)
            weakSelf.dismiss()
        }

        let tap = UITapGestureRecognizer()
        tap.delegate = self
        addGestureRecognizer(tap)

        tap.rx.event.subscribe { [weak self] _ in
            guard let weakSelf = self, let model = weakSelf.model else { return }
            weakSelf.saveConfig(model)
            weakSelf.dismiss()
        }.disposed(by: rx.disposeBag)

        editFieldContentView.submitBlock = { [weak self] indexPath, model in
            guard let weakSelf = self else { return }
            weakSelf.tableView.reloadRows(at: [indexPath], with: .none)
        }

        WmcDateManager.shared.networkDate.subscribe(onNext: { [weak self] value in
            guard let weakSelf = self else { return }
            let time = value ?? Date()
            let timeStr = time.yp.string("yyyy-MM-dd hh:mm", identifier: .asia(.Shanghai))

            var indexPath: IndexPath?
            var model: WmcWatermarkOptionModel?
            for (idx, item) in weakSelf.viewModel.dataSource.enumerated() {
                if item.fieldType == .time {
                    model = item
                    indexPath = IndexPath(row: idx, section: 0)
                    break
                }
            }

            guard let indexPath = indexPath, let model = model else { return }

            if model.content != timeStr {
                model.content = timeStr
                weakSelf.tableView.reloadRows(at: [indexPath], with: .none)
            }
        }).disposed(by: rx.disposeBag)
    }
    
    private func saveConfig(_ model: WmcWatermarkDetailModel) {
        confirmClosure?(model)
        viewModel.saveConfig(model)
    }
}

// MARK: - UITableViewDelegate, UITableViewDataSource

extension WmcRecognitionSettingsView: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in _: UITableView) -> Int {
        return 1
    }

    func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
        return viewModel.dataSource.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: WmcRecognitionSettingsListCell = tableView.dequeueReusableCell(withIdentifier: "WmcRecognitionSettingsListCell", for: indexPath) as! WmcRecognitionSettingsListCell
        if let model = viewModel.dataSource.yp.object(at: indexPath.row) {
            cell.bindModel(model, indexPath: indexPath)
            cell.switchClosure = { [weak self] data in
                guard let weakSelf = self else { return }
                model.isOpen = data.isOn
                weakSelf.tableView.reloadRows(at: [data.indexPath], with: .none)
            }
            cell.singleClickClosure = { [weak self] data in
                guard let weakSelf = self else { return }
                if let text = model.options.yp.object(at: data.optionIndex) {
                    model.content = text
                    model.isOpen = true
                    weakSelf.tableView.reloadRows(at: [data.indexPath], with: .none)
                }
            }
        }
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let model = viewModel.dataSource.yp.object(at: indexPath.row) else { return }
        if model.fieldType == .remark {
            let vm = WmcRemarkVM()
            vm.remarkText = model.content
            WmcNavigatorManager.push(.remark, parms: vm)
            vm.submitRemarkRelay.subscribe(onNext: { [weak self] remark in
                guard let weakSelf = self else { return }
                model.content = remark
                model.isOpen = !remark.isEmpty
                weakSelf.tableView.reloadRows(at: [indexPath], with: .none)
            }).disposed(by: rx.disposeBag)
        } else if model.fieldType == .text || model.fieldType == .length {
            editFieldContentView.configModel(model)
            editFieldContentView.indexPath = indexPath

            let config: WmcPresentVC.Config = .init(style: .notice(), contentView: editFieldContentView, contentLayoutBlock: { make in
                make.top.equalTo(Wmc_safeAreaTop)
                make.left.right.equalToSuperview()
                var height = 70
                if model.enableEditTitle {
                    height += 95
                }
                if model.enableEditContent {
                    height += 180
                }
                make.height.equalTo(height.wmc_autoVer)
            })

            editFieldContentView.show(config: config) { [weak self] in
                guard let weakSelf = self else { return }
                weakSelf.editFieldContentView.setFirstResponder() // 弹出键盘
            }
        }
    }

    func tableView(_: UITableView, heightForRowAt _: IndexPath) -> CGFloat {
        return 57
    }
}

// MARK: - UIGestureRecognizerDelegate

extension WmcRecognitionSettingsView: UIGestureRecognizerDelegate {
    override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        let point = gestureRecognizer.location(in: self)
        return !contentView.frame.contains(point)
    }
}
